<?php

/**
 */
class EntityToArrayConverter {

    private $propertiesArePublic = false;
    private $getPrefix = "get";

    public function __construct($propertiesArePublic = false) {
        $this->propertiesArePublic = $propertiesArePublic;
    }

    /**
     * @return array 
     */
    public function convert($entity) {
        if (is_string($entity) || is_scalar($entity)) {
            return $entity;
        }

        $result = array();

        if (is_array($entity)) {
            foreach ($entity as $key => $object) {
                if (is_numeric($key)) {
                    $result[] = $this->convert($object);
                } else {
                    $result[$key] = $this->convert($object);
                }
            }
            return $result;
        }

        if (!$this->propertiesArePublic) {
            $reflectedObject = new ReflectionClass($entity);
            foreach ($reflectedObject->getProperties() as /* @var $property ReflectionProperty */$property) {

                $getter = $this->getPrefix . ucfirst($property->name);
                if ($reflectedObject->hasMethod($getter)) {

                    $propertyValue = $entity->{$getter}();
                    $index = $property->name;

                    if (!is_object($propertyValue) && !is_array($propertyValue)) {
                        $result[$index] = $propertyValue;
                    } else {
                        $result[$index] = $this->convert($propertyValue);
                    }
                }
            }
        } else {
            $result = get_object_vars($entity);
        }

        return $result;
    }

}

?>